//
// Created by 徐套 on 2023/9/19.
//
//子服务器代码，主要功能负责初始化服务器，初始化连接客户端
// tcp连接发送心跳包，小车状态
// udp连接发送小车状态参数

#ifndef CAR_CLOUD_SERVER_SERVER_H
#define CAR_CLOUD_SERVER_SERVER_H


#include <string>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <thread>
#include "common/clock.hpp"
#include "code_c/car_state.h"

#define MAXTIME 2
#define MAXRECV 1024


class cloud_server {
public:
    std::string name_sign;
    cloud_server(const char *str_ip, unsigned int u_port, int client, Clock_time *time0);
    ~cloud_server();

    // 初始化服务器
    bool init_server();

    // 通过udp协议接收数据
    void recv_msg_by_udp();

    // 启动服务器
    void begin();

    // 通过tcp协议接收数据
    void recv_msg_by_tcp();

    // 心跳包检测，时延检测
    void heart_beat_time();

    // 通过tcp协议发送指令
    bool send_msg_by_tcp(char* msg);

    void send_msg_by_udp(std::string &msg);

    std::string get_name() const;

    // 反馈当前车辆延时信息
    unsigned int get_time_late() const;

    // 判断服务器是否持续
    bool is_alive() const;

    CarState* get_now_state();

private:
    bool tcp_error_;
    bool hreat_error_;
    unsigned int local_port_tcp;
    unsigned int local_port_udp;
    std::string m_str_ip;
    struct sockaddr_in client_addr_;
    socklen_t client_len_;
    int m_client_socket_udp;// = socket(AF_INET, SOCK_STREAM, 0);
    int m_client_socket_tcp;// = socket(AF_INET, SOCK_STREAM, 0);
    bool start;
    Clock_time* time_right;
    unsigned int time_out;
    CarState car_;
    int heart_num;
};


#endif //CAR_CLOUD_SERVER_SERVER_H
